package com.airnews.ticket.ui.flight;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.airnews.ticket.R;
import com.airnews.ticket.adapter.MySimpleAdapter;
import com.airnews.ticket.model.FlightInfo;
import com.airnews.ticket.model.SearchFlight;
import com.airnews.ticket.sql.FavoriteInfoDB;
import com.airnews.ticket.ui.BaseActivity;
import com.airnews.ticket.util.Utils;
import com.mobclick.android.MobclickAgent;

public class PassengerList extends BaseActivity implements
		AdapterView.OnItemClickListener {

	private final static int DELETE_DIALOG = 1;
	public static List<Map<String,String>> passengerList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> mileagerInfoList = new ArrayList<Map<String,String>>();
	
	public static FlightInfo flight;//去程
	public static FlightInfo returnFlight;//回程
	public static SearchFlight searchFlight;
	private Button backBut;
	public PassengerAdapter sa;
	public ListView lv;
	public Button mBtnBack,mBtnNext,passengerSaveBut,button_add_passenger,button_update_passenger,select_person_ok;
	public List<Map<String, String>> data = new ArrayList<Map<String, String>>();

	
	private static int position;
	private TextView no_passenger_alert ;
	

    public List<Map<String, String>> positionSelectList = new ArrayList<Map<String, String>>();//选定的
	private int editCount = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.passenger_list);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);
		
		passengerList = FavoriteInfoDB.selectPsgInfoList(PassengerList.this);
		
		lv = (ListView) findViewById(R.id.passenger_list);
		
		preAdapterData();
		
		lv.setOnItemClickListener(this);
		
		no_passenger_alert = (TextView)findViewById(R.id.no_passenger_alert);
		if(passengerList.size() != 0) {
			no_passenger_alert.setVisibility(View.GONE);
			Utils.setListViewHeightBasedOnChildren(lv);//更新list高度
			sa.notifyDataSetChanged();
		} else {
			no_passenger_alert.setVisibility(View.VISIBLE);
			no_passenger_alert.setText("暂未添加登机人 ！");
		}
		
		backBut = (Button)findViewById(R.id.backBut);
		backBut.setOnClickListener(b_ocl);
		
		button_add_passenger = (Button)findViewById(R.id.button_add_passenger);
		button_add_passenger.setOnClickListener(b_ocl);
		
		button_update_passenger = (Button)findViewById(R.id.button_update_passenger);
		button_update_passenger.setOnClickListener(b_ocl);
		
		select_person_ok = (Button)findViewById(R.id.select_person_ok);
		select_person_ok.setOnClickListener(b_ocl);
		
	}
	
	private void preAdapterData(){
		sa = new PassengerAdapter(
				this,
				passengerList,
				R.layout.flight_passenger_item,
				new String[] { "passengerName", "passengerIdNumber"},
				new int[] { R.id.passenger_name, R.id.passenger_id_number}); //name<=>psgName,paperType<=>idType,idNo<=>paperNo
		lv.setAdapter(sa);
		sa.notifyDataSetChanged();
	}
	
	OnClickListener b_ocl= new OnClickListener() { 
    	public void onClick(View v) { 
    		switch (v.getId()) {
	    		case R.id.backBut:
	    			Intent intent3 = new Intent();
	    			intent3.setClass(PassengerList.this, FlyOrderInput.class);
	    			FlyOrderInput.flight = flight;
					FlyOrderInput.returnFlight = returnFlight;
					FlyOrderInput.searchFlight = searchFlight;
//					FlyOrderInput.mileagerInfoList = mileagerInfoList;
//					FlyOrderInput.passengerList = passengerList;
	    			startActivity(intent3);
	    			break;
	    		case R.id.button_add_passenger:
	    			Intent intent = new Intent();
	    			intent.setClass(PassengerList.this, PassengerAdd.class);
	    			startActivity(intent);
	    			break;
	    		case R.id.button_update_passenger:
	    			editCount++;
	    			preAdapterData();
	    			passengerList = FavoriteInfoDB.selectPsgInfoList(PassengerList.this);//重新查询
	    			break;
	    		case R.id.select_person_ok:
	    			boolean isDouble = false;
	    			for(int p = 0;p < positionSelectList.size();p++){
	    				Map<String,String> positionSelMap = positionSelectList.get(p);
	    				for (int i = 0; i < FlyOrderInput.passengerList.size(); i++) {
		    				Map m = FlyOrderInput.passengerList.get(i);
		    				if (positionSelMap.get("passengerIdNumber").equals(m.get("passengerIdNumber"))) {
		    					Toast.makeText(PassengerList.this, m.get("passengerName") + "已添加该乘客信息", Toast.LENGTH_LONG).show();
		    					isDouble = true;
		    					break;
		    				} else {
		    					isDouble = false;
		    				}
		    			}
	    				if(!isDouble){
		    				Map<String ,String> addMap = new HashMap<String ,String>();
		    				System.out.println("选定的登机人号：" + positionSelMap.get("passengerIDNo") + ";类型："+positionSelMap.get("passengerIDType"));
		    				addMap.put("passengerIdNumber", positionSelMap.get("passengerIdNumber"));
		    				addMap.put("passengerName", positionSelMap.get("passengerName"));
		    				addMap.put("passagerBirthday", positionSelMap.get("passagerBirthday"));
		    				addMap.put("passengerMobile", positionSelMap.get("passengerMobile"));
		    				addMap.put("email", positionSelMap.get("email"));
		    				addMap.put("sex", positionSelMap.get("sex"));
		    				addMap.put("passengerIDNo", positionSelMap.get("passengerIDNo"));
		    				addMap.put("passengerIDType", positionSelMap.get("passengerIDType"));
		    				FlyOrderInput.passengerList.add(addMap);
	    				}
	    			}
	    			Intent intentI = new Intent();
	    			intentI.setClass(PassengerList.this, FlyOrderInput.class);

					FlyOrderInput.flight = flight;
					FlyOrderInput.returnFlight = returnFlight;
					FlyOrderInput.searchFlight = searchFlight;
					startActivity(intentI);
					
	    			break;
    		}
    	}
	};
	
	public void onItemClick(AdapterView<?> adaView, View v, int position,
			long arg3) {
		Intent intenthistory = new Intent(PassengerList.this,PassengerEdit.class);
      	intenthistory.putExtra("position", position);
      	PassengerEdit.flight = flight;
      	PassengerEdit.data = passengerList;
      	PassengerEdit.searchFlight = searchFlight;
		startActivity(intenthistory);
	}
	
	public Dialog onCreateDialog(int id) {
		switch (id) {
			case DELETE_DIALOG:
				return buildDeleteDialog();
		}
		return null;
	}

	private Dialog buildDeleteDialog() {
		 return new AlertDialog.Builder(this)
         .setTitle("请选择")
         .setItems(R.array.dialog_passenger_list_f, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {
            	 if(which==0){
		    			Map<String ,String> removeMap = passengerList.get(position);
		    			for (int i = 0; i < FlyOrderInput.passengerList.size(); i++) {
		    				Map m = FlyOrderInput.passengerList.get(i);
		    				if (removeMap.get("passengerIDNo").equals(m.get("passengerIDNo"))) {
		    					Toast.makeText(PassengerList.this, "已添加该乘客信息", Toast.LENGTH_LONG).show();
		    					return;
		    				}
		    			}
		    			FlyOrderInput.passengerList.add(removeMap);
		    			Intent intent = new Intent();
						intent.setClass(PassengerList.this, FlyOrderInput.class);

						FlyOrderInput.flight = flight;
						FlyOrderInput.returnFlight = returnFlight;
						FlyOrderInput.searchFlight = searchFlight;
						startActivity(intent);
                  }
                 if(which==1){
                	Intent intenthistory = new Intent(PassengerList.this,PassengerEdit.class);
                  	intenthistory.putExtra("position", position);
                  	PassengerEdit.flight = flight;
                  	PassengerEdit.data = passengerList;
                  	PassengerEdit.searchFlight = searchFlight;
     				startActivity(intenthistory);
                 }else if(which==2){
                	Map<String ,String> removeMap = passengerList.remove(position);
             		if(passengerList.size() != 0) {
            			no_passenger_alert.setVisibility(View.GONE);
            			Utils.setListViewHeightBasedOnChildren(lv);
                    	sa.notifyDataSetChanged();
            		} else {
            			no_passenger_alert.setVisibility(View.VISIBLE);
            			lv.setVisibility(View.GONE);
            			no_passenger_alert.setText("暂未添加登机人 ！");
            		}
             		FavoriteInfoDB.deletePsgInfo(PassengerList.this, removeMap.get("passengerName"),removeMap.get("passengerIDNo"));
                 }
             }
         })
         .create();
	}
	

	private class PassengerAdapter extends MySimpleAdapter {
  		
		public PassengerAdapter(Context context, List<? extends Map<String, ?>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}
  		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final View v = super.getView(position, convertView, parent);
			final CheckBox checkPassenger = (CheckBox) v.findViewById(R.id.checkPassenger);
			checkPassenger.setClickable(true);
			checkPassenger.setVisibility(View.VISIBLE);
			TextView passengerNameView = (TextView) v.findViewById(R.id.passenger_name);
			final String passengerName  = passengerNameView.getText().toString();
			TextView numberView = (TextView) v.findViewById(R.id.passenger_id_number);
			final String number  = numberView.getText().toString();
			checkPassenger.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					Map<String,String> positionSelect = passengerList.get(position);//new HashMap<String,String>();//选定的
					if(checkPassenger.isChecked()){
//						positionSelect.put("passengerIDNo", number);
//						positionSelect.put("passengerName", passengerName);
						positionSelectList.add(positionSelect);
					}else {
//						positionSelect.remove(number);//存放的是号码的值
//						positionSelect.remove(passengerName);//存放的是号码的值
						positionSelectList.remove(positionSelect);
					}
				}
			});
			Button delButton  = (Button) v.findViewById(R.id.delete_order_passenger);
			if(editCount%2==1){
				delButton.setVisibility(View.VISIBLE);
				checkPassenger.setVisibility(View.GONE);
				delButton.setOnClickListener(new OnClickListener() {
					public void onClick(View view) {
						showDeleteDialog(position,number);
					}
				});
			}

			final Map<String ,String> removeMap = passengerList.get(position);
			final Button setDefaultButton  = (Button) v.findViewById(R.id.set_as_default);
			if(removeMap.get("setDefault")!=null && removeMap.get("setDefault").equals("1")){
				setDefaultButton.setVisibility(View.VISIBLE);
				delButton.setVisibility(View.GONE);
				checkPassenger.setVisibility(View.VISIBLE);
				setDefaultButton.setBackgroundDrawable(PassengerList.this.getResources().getDrawable(R.drawable.default_contact_bg));
			} 
			if(editCount%2==1){
				setDefaultButton.setVisibility(View.VISIBLE);
				delButton.setVisibility(View.VISIBLE);
				checkPassenger.setVisibility(View.GONE);
				if(removeMap.get("setDefault")!=null && removeMap.get("setDefault").equals("1")){
					setDefaultButton.setBackgroundDrawable(PassengerList.this.getResources().getDrawable(R.drawable.cancel_default));
					setDefaultButton.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							ContentValues values = new ContentValues();
							values.put("passengerName", removeMap.get("passengerName"));
							values.put("idNo", removeMap.get("passengerIDNo"));
							values.put("setDefault", "0");//设置为取消默认值
							FavoriteInfoDB.updatePsgInfo(PassengerList.this, values);
							setDefaultButton.setBackgroundDrawable(PassengerList.this.getResources().getDrawable(R.drawable.set_as_default));
							editCount++;
							passengerList = FavoriteInfoDB.selectPsgInfoList(PassengerList.this);
			    			preAdapterData();
						}
					});
				} else {
					setDefaultButton.setBackgroundDrawable(PassengerList.this.getResources().getDrawable(R.drawable.set_as_default));
					setDefaultButton.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							ContentValues values = new ContentValues();
							values.put("passengerName", removeMap.get("passengerName"));
							values.put("idNo", removeMap.get("passengerIDNo"));
							values.put("setDefault", "1");//设置为默认值
							FavoriteInfoDB.updatePsgInfo(PassengerList.this, values);
							setDefaultButton.setBackgroundDrawable(PassengerList.this.getResources().getDrawable(R.drawable.cancel_default));
							editCount++;
							passengerList = FavoriteInfoDB.selectPsgInfoList(PassengerList.this);
			    			preAdapterData();
						}
					});
				}
			}
			return v;
		}
  	}
	
	//删除联系人
	private void showDeleteDialog(final int pos,final String number){   
		AlertDialog.Builder builder = new AlertDialog.Builder(this);    
		builder.setTitle("删除登机人");    
		builder.setMessage("真的要删除此条记录吗？");    
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {    
		public void onClick(DialogInterface dialog, int which) {   
			for(Map<String,String> map :passengerList){
				if(map.get("passengerIdNumber").equals(number)){
					passengerList.remove(map);
					FlyOrderInput.passengerList.remove(map);
					FavoriteInfoDB.deletePsgInfo(PassengerList.this, map.get("passengerName"),map.get("passengerIDNo"));
					break;
				}
			}
			if(passengerList.size() != 0) {
    			no_passenger_alert.setVisibility(View.GONE);
    			Utils.setListViewHeightBasedOnChildren(lv);
            	sa.notifyDataSetChanged();
    		} else {
    			no_passenger_alert.setVisibility(View.VISIBLE);
    			lv.setVisibility(View.GONE);
    			no_passenger_alert.setText("暂未添加登机人 ！");
    		}
			preAdapterData();
		}    
		});    
		   
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {    
		public void onClick(DialogInterface dialog, int which) {    
		dialog.cancel();    
		}    
		});    
		   
		AlertDialog ad = builder.create();    
		ad.show();    
	} 
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
